//
//  StatusHelper.swift
//  ifanr
//
//  Created by 😱😱 on 16/9/16.
//  Copyright © 2016年 😱😱. All rights reserved.
//

import UIKit
import FMDB
import SwiftyJSON

class StatusHelper {
    private static let db:FMDatabase = {
        let databasePath = try! NSFileManager.defaultManager()
            .URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
            .URLByAppendingPathComponent("status.sqlite")
        let db = FMDatabase(path: databasePath.path)
        db.open()
        do {
            try db.executeUpdate("CREATE TABLE IF NOT EXISTS t_status (id integer PRIMARY KEY, status blob NOT NULL, pubdate text NOT NULL, idstr text NOT NULL);", values: nil)
        }
        catch let error as NSError {
            print("failed: \(error.localizedDescription)")
        }
        return db
    }()

    
    // 缓存到数据库
    static func homeStatusWithPage(page: Int) -> [AnyObject] {
        let page = (page - 1) * 12
        var sql = ""
        if page == 0 {
            sql = "SELECT * FROM t_status ORDER BY pubdate DESC LIMIT 12;"
        } else {
            sql = "SELECT * FROM t_status ORDER BY pubdate DESC LIMIT 12 OFFSET \(page);"
        }
        var statuses = [AnyObject]()
        do {
            try db.executeQuery(sql, values: nil)
            let rs = try db.executeQuery(sql, values: nil)
            
            while rs.next() {
                let statusData = rs.objectForColumnIndex(1) as! NSData
                statuses.append(NSKeyedUnarchiver.unarchiveObjectWithData(statusData)!)
            }
        } catch let error as NSError {
            print("failed: \(error.localizedDescription)")
        }
        return statuses;
    }
    
    static func saveStatus(statuses:[JSON]) {
        for status in statuses {
            let status = status.dictionaryObject!
            var data: NSData = NSData()
            data = NSKeyedArchiver.archivedDataWithRootObject(status as AnyObject)
            do {
                try db.executeUpdate("insert into t_status (status, pubdate, idstr) values (?,?,?)", values: [data, status["post_timestamp"]!.stringValue, status["ID"]!.stringValue])
            }
            catch let error as NSError {
                print("failed: \(error.localizedDescription)")
            }
        }
    }

    private init(){}
}
